/*
 * @Author: xushuhao
 * @Email: xshmouse@163.com
 * @Date: 2020-04-23 09:06:42
 * @Last Modified by: xushuhao
 * @Last Modified time: 2020-07-28 08:41:45
 * @Description: 我的页面 - TabBar导航
 */

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_code_framework/base/base_widget.dart';
import 'package:flutter_code_framework/demo/demo_page.dart';
import 'package:flutter_code_framework/model_data/user/data.dart';
import 'package:flutter_code_framework/pages/login.dart';
import 'package:flutter_code_framework/route/route_transition.dart';
import 'package:flutter_code_framework/utils/global.dart';
import 'package:flutter_code_framework/widgets/single_media_picker_widget.dart';
import 'package:image_picker/image_picker.dart';

class MyPage extends BaseWidget {
  MyPage({Key key}) : super(key: key);
  // final Map args;

  // MyPage({this.args});

  @override
  BaseWidgetState<BaseWidget> getState() {
    return _MyPageState();
  }
}

class _MyPageState extends BaseWidgetState<MyPage> {
  Map args;
  ImageProvider<dynamic> userHeadImg;
  String vertionInfo = "";
  TextEditingController oldPasswordInputController = TextEditingController();
  TextEditingController newPasswordInputController = TextEditingController();
  TextEditingController renewPasswordInputController = TextEditingController();

//学段 Picker

  FixedExtentScrollController periodScrollController =
      FixedExtentScrollController(initialItem: 0);
  Map<String, Object> periodPickerValue = {"id": -1, "name": "请选择"};
  List<dynamic> periodList = [];
  setPeriodPickerValue(int index) {
    setState(() {
      periodPickerValue = periodList[index];
      refreshInitData();
    });
    //执行保存逻辑
    saveForm();
  }

//年级 Picker
  FixedExtentScrollController gradeScrollController =
      FixedExtentScrollController(initialItem: 0);
  Map<String, Object> gradePickerValue = {"id": -1, "name": "请选择"};
  List<dynamic> gradeList = [];
  setGradePickerValue(int index) {
    setState(() {
      gradePickerValue = gradeList[index];
      gradeScrollController = FixedExtentScrollController(initialItem: index);
    });
    //执行保存逻辑
    saveForm();
  }

  //学科 Picker
  FixedExtentScrollController subjectScrollController =
      FixedExtentScrollController(initialItem: 0);
  Map<String, Object> subjectPickerValue = {"id": -1, "name": "请选择"};
  List<dynamic> subjectList = [];
  setSubjectPickerValue(int index) {
    setState(() {
      subjectPickerValue = subjectList[index];
      subjectScrollController = FixedExtentScrollController(initialItem: index);
    });
    //执行保存逻辑
    saveForm();
  }

//职称 Picker
  FixedExtentScrollController jobScrollController =
      FixedExtentScrollController(initialItem: 0);
  Map<String, Object> jobPickerValue = {"id": -1, "name": "请选择"};
  List<dynamic> jobList = [];
  setJobPickerValue(int index) {
    setState(() {
      jobPickerValue = jobList[index];
      jobScrollController = FixedExtentScrollController(initialItem: index);
    });
    //执行保存逻辑
    saveForm();
  }

  Future onsubmit(String v) async {
    if (oldPasswordInputController.value.text.trim() == "" ||
        newPasswordInputController.value.text.trim() == "" ||
        renewPasswordInputController.value.text.trim() == "") {
      return;
    }
    //验证、保存
    if (newPasswordInputController.value.text.trim() !=
        renewPasswordInputController.value.text.trim()) {
      // G.toast('新密码和确认密码不一致');
      showWrongToast('新密码和确认密码不一致');
      return;
    }
    G.req.user
        .rePassword(
            oldPassword: oldPasswordInputController.value.text,
            newPassword: newPasswordInputController.value.text)
        .then((rs) {
      if (rs.data['isOk'] == true) {
        showRightToast('修改成功！');
        //需清空数据，并收起浮
        oldPasswordInputController.clear();
        newPasswordInputController.clear();
        renewPasswordInputController.clear();
        Navigator.pop(context);
      }
    });
  }

  @override
  Widget buildWidget(BuildContext context) {
    FocusNode oldPasswordNode = FocusNode();
    FocusNode newPasswordNode = FocusNode();
    FocusNode renewPasswordNode = FocusNode();

    Widget headWidget = Container(
      height: 44,
      width: double.infinity,
      color: Theme.of(context).backgroundColor,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          GestureDetector(
            child: Container(
                padding: EdgeInsets.fromLTRB(24, 0, 10, 0),
                color: Theme.of(context).backgroundColor,
                child: Text('')),
            onTap: () {},
          ),
          Expanded(
              child: Center(
            child: Text('',
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    fontSize: 18,
                    color: Theme.of(context).primaryTextTheme.headline2.color)),
          )),
          Container(
            child: GestureDetector(
              child: Container(
                padding: EdgeInsets.fromLTRB(20, 5, 0, 5),
                color: Colors.transparent,
                child: Text(
                  '修改密码',
                  style: TextStyle(
                      color: Theme.of(context).primaryTextTheme.caption.color,
                      fontSize: 16),
                ),
              ),
              onTap: () {
                showBottomSheetDialog(Container(
                    height: 312.0,
                    color: Colors.transparent,
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(24, 36, 24, 30),
                      child: Column(
                        children: <Widget>[
                          TextField(
                            // autofocus: true,
                            focusNode: oldPasswordNode,
                            decoration: InputDecoration(
                                labelText: "原密码",
                                hintText: "请输入您目前的密码",
                                prefixIcon: Icon(Icons.person)),
                            obscureText: true,
                            controller: oldPasswordInputController,
                            onSubmitted: (v) {
                              onsubmit(v);
                              // FocusScope.of(context)
                              //     .requestFocus(newPasswordNode);
                            },
                          ),
                          TextField(
                            focusNode: newPasswordNode,
                            decoration: InputDecoration(
                                labelText: "新密码",
                                hintText: "请输入您的新密码",
                                prefixIcon: Icon(Icons.lock)),
                            obscureText: true,
                            controller: newPasswordInputController,
                            onSubmitted: (v) {
                              onsubmit(v);
                              // FocusScope.of(context)
                              //     .requestFocus(renewPasswordNode);
                            },
                          ),
                          TextField(
                            focusNode: renewPasswordNode,
                            decoration: InputDecoration(
                                labelText: "新密码确认",
                                hintText: "请重新输入您的新密码",
                                prefixIcon: Icon(Icons.lock)),
                            obscureText: true,
                            controller: renewPasswordInputController,
                            onSubmitted: (v) {
                              onsubmit(v);
                            },
                          ),
                        ],
                      ),
                    )));
              },
            ),
          ),
        ],
      ),
    );

    Widget headPic = Container(
      height: 181,
      width: double.infinity,
      child: Column(
        children: <Widget>[
          Container(
            height: 6,
            child: Text(''),
          ),
          Center(
            child: GestureDetector(
              child: Container(
                height: 105,
                width: 105,
                decoration: BoxDecoration(
                  border: Border.all(
                      width: 3.5, color: Theme.of(context).primaryColor),
                  borderRadius: BorderRadius.circular(100),
                ),
                child: CircleAvatar(
                  backgroundColor: Colors.transparent,
                  backgroundImage: userHeadImg,
                ),
              ),
              onTap: () {
                showBottomSheetDialog(Container(
                  height: 208.0,
                  padding: EdgeInsets.fromLTRB(0, 23, 0, 23),
                  child: SingleMediaPickerWidget(
                    mediaType: MediaType.image,
                    callback: (PickedFile file) {
                      Future.delayed(Duration(milliseconds: 200)).then((e) {
                        setState(() {
                          //本地显示
                          userHeadImg = FileImage(File(file.path));
                        });
                      });
                      //上传头像
                      G.req.common.updateImage(file.path).then((rs) {
                        if (rs.data['isOk'] != false) {
                          G.user.data.headPic = rs.data['url'];
                          G.req.user.updateHeadImage(key: rs.data['name']);
                        }
                      });
                    },
                  ),
                ));
              },
            ),
          ),
          Container(
            height: 11,
            child: Text(''),
          ),
          Text(
            G.user.data.userName,
            style: TextStyle(
                color: Theme.of(context).primaryTextTheme.caption.color,
                fontSize: 18),
          ),
          Container(
            height: 5,
            child: Text(''),
          ),
          Text(G.user.data.schoolName,
              style: TextStyle(
                  color: Theme.of(context).primaryTextTheme.caption.color,
                  fontSize: 14)),
        ],
      ),
    );

    getGradeWiget(String _lable, Widget _picker) {
      return Container(
          height: 100,
          color: Colors.transparent,
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(0, 15, 0, 0),
                    child: Text(
                      _lable,
                      style: TextStyle(
                          color:
                              Theme.of(context).primaryTextTheme.caption.color,
                          fontSize: 18),
                    ),
                  ),
                ],
              ),
              Row(
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(0, 0, 0, 9),
                    child: _picker,
                  ),
                ],
              ),
              Divider(
                height: 1,
                color: Theme.of(context).primaryTextTheme.caption.color,
              ),
            ],
          ));
    }

    //授课学段
    Widget periodInfo = Container(
      color: Colors.transparent,
      alignment: Alignment.centerLeft,
      width: MediaQuery.of(context).size.width - 48,
      height: 48,
      child: Text(periodPickerValue["name"],
          style: TextStyle(
            color: Theme.of(context).primaryTextTheme.caption.color,
            fontSize: 14,
          )),
    );
    //授课年级
    Widget gradeInfo = Container(
      color: Colors.transparent,
      alignment: Alignment.centerLeft,
      width: MediaQuery.of(context).size.width - 48,
      height: 48,
      child: Text(gradePickerValue["name"],
          style: TextStyle(
            color: Theme.of(context).primaryTextTheme.caption.color,
            fontSize: 14,
          )),
    );
    //授课年级
    Widget subjectInfo = Container(
      color: Colors.transparent,
      alignment: Alignment.centerLeft,
      width: MediaQuery.of(context).size.width - 48,
      height: 48,
      child: Text(subjectPickerValue["name"],
          style: TextStyle(
            color: Theme.of(context).primaryTextTheme.caption.color,
            fontSize: 14,
          )),
    );

    //职称
    Widget jobInfo = Container(
      color: Colors.transparent,
      alignment: Alignment.centerLeft,
      width: MediaQuery.of(context).size.width - 48,
      height: 48,
      child: Text(jobPickerValue["name"],
          style: TextStyle(
            color: Theme.of(context).primaryTextTheme.caption.color,
            fontSize: 14,
          )),
    );

    Widget infoList = Padding(
        padding: EdgeInsets.fromLTRB(0, 17, 0, 25),
        child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              getGradeWiget(
                  '授课学段',
                  showPickerList(context, periodScrollController, periodList,
                      periodInfo, setPeriodPickerValue)),
              getGradeWiget(
                  '授课年级',
                  showPickerList(context, gradeScrollController, gradeList,
                      gradeInfo, setGradePickerValue)),
              getGradeWiget(
                  '授课学科',
                  showPickerList(context, subjectScrollController, subjectList,
                      subjectInfo, setSubjectPickerValue)),
              getGradeWiget(
                  '职称',
                  showPickerList(context, jobScrollController, jobList, jobInfo,
                      setJobPickerValue)),
            ]));

    Widget bottomWidget = Container(
      height: 336,
      padding: EdgeInsets.fromLTRB(0, 112, 0, 72),
      child: Column(
        children: <Widget>[
          GestureDetector(
            child: Padding(
              padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
              child: Text(
                vertionInfo,
                textAlign: TextAlign.center,
                style: TextStyle(
                    color: Theme.of(context).primaryTextTheme.headline1.color,
                    fontSize: 14),
              ),
            ),
            onDoubleTap: () {
              RouteTransition(DemoPage()).pushTransRoute(context);
            },
          ),
          GestureDetector(
            child: Container(
              height: 46,
              width: double.infinity,
              decoration: BoxDecoration(
                  color: Theme.of(context).primaryColor,
                  borderRadius: BorderRadius.circular(5.0)),
              child: Center(
                child: Text(
                  '退出登录',
                  style: TextStyle(
                      // height: 6,
                      color: Theme.of(context).primaryTextTheme.button.color,
                      fontSize: 16),
                ),
              ),
            ),
            onTap: () {
              //clear password!
              var userCode = G.user.data.code;
              G.user.delUserInfo();
              G.user.setData(UserData(code: userCode));
              G.tabIndex = 0;
              RouteTransition(Login()).pushAndRemoveUntilTransRoute(context);
            },
          ),
        ],
      ),
    );

    return Container(
      padding: EdgeInsets.fromLTRB(24, 0, 24, 0),
      height: getMainWidgetHeight() - kTabbarHeigt,
      child: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            headWidget,
            headPic,
            infoList,
            bottomWidget,
          ],
        ),
      ),
    );
  }

  initPeroidDataList() async {
    //学段
    var _period = await G.req.periodData.getList();
    if (_period.data != null && _period.data['periodList'].length > 0) {
      setState(() {
        periodList = _period.data['periodList'];
      });
    }
    //职称
    var _jobTitle = await G.req.common.getJobTitlelist();
    if (_jobTitle.data['isOK'] != false) {
      var tepJob = [];
      _jobTitle.data['list'].forEach((element) {
        tepJob.add({"id": element["Id"], "name": element['Name']});
      });
      setState(() {
        jobList = tepJob;
      });
    }
  }

  refrehBaseList() async {
    //年级
    var _grade = await G.req.gradeData
        .getList(periodId: periodPickerValue["id"].toString());
    if (_grade.data != null && _grade.data['gradeList'].length > 0) {
      setState(() {
        gradeList = _grade.data['gradeList'];
      });
    }

    //学科
    var _subject = await G.req.subjectData.getList(
        schoolId: G.user.data.schoolId.toString(),
        periodId: periodPickerValue['id'].toString());
    if (_subject.data['subjectList'].length > 0) {
      if (mounted) {
        setState(() {
          subjectList = _subject.data['subjectList'];
        });
      }
    }
  }

  refreshInitData() async {
    await refrehBaseList();
    gradePickerValue = gradeList[0];
    gradeScrollController = FixedExtentScrollController(initialItem: 0);
    subjectPickerValue = subjectList[0];
    subjectScrollController = FixedExtentScrollController(initialItem: 0);
  }

  initBaseData() async {
    await initPeroidDataList();
    //加载数据
    if (jobList != []) {
      setState(() {
        jobPickerValue = jobList.firstWhere(
            (element) => element['name'] == G.user.data.jobTitle, orElse: () {
          return {"id": -1, "name": "请选择"};
        });
      });
    }

    if (periodList != null && periodList.length > 0) {
      if (mounted) {
        setState(() {
          periodPickerValue = periodList.firstWhere(
              (element) => element['id'] == G.user.data.periodId, orElse: () {
            return periodList[0];
          });
          periodScrollController = FixedExtentScrollController(
              initialItem: periodList.indexOf(periodPickerValue));
        });
      }
    }
    await refrehBaseList();
    //加载数据
    if (subjectList != null && subjectList.length > 0) {
      setState(() {
        subjectPickerValue = subjectList.firstWhere(
            (element) => element['id'] == G.user.data.subjectId, orElse: () {
          return subjectList[0];
        });
        subjectScrollController = FixedExtentScrollController(
            initialItem: subjectList.indexOf(subjectPickerValue));
      });
    }
    if (gradeList != null && gradeList.length > 0) {
      setState(() {
        gradePickerValue = gradeList.firstWhere(
            (element) => element['id'] == G.user.data.gradeId, orElse: () {
          return gradeList[0];
        });
        gradeScrollController = FixedExtentScrollController(
            initialItem: gradeList.indexOf(gradePickerValue));
      });
    }
  }

  saveForm() async {
    await G.req.userGuide.guide(
        subjectId: subjectPickerValue['id'] as int,
        periodId: periodPickerValue['id'] as int,
        gradeId: gradePickerValue['id'] as int,
        jobTitle:
            jobPickerValue['name'] == '请选择' ? '' : jobPickerValue['name']);
    //     .then((rs) {
    //   if (rs.data['isOk'] == true) {
    //     G.user.data.subjectId = subjectPickerValue['id'] as int;
    //     G.user.data.periodId = periodPickerValue['id'] as int;
    //     G.user.data.gradeId = gradePickerValue['id'] as int;
    //     G.user.data.jobTitle = jobPickerValue['name'];
    //   }
    // });
  }

  @override
  void initState() {
    super.initState();
    userHeadImg = NetworkImage(G.user.data.headPic);

    //初始化基础数据
    initBaseData();

    vertionInfo = 'CKXT-Teacher ';
    Future.delayed(Duration(seconds: 1)).then((value) {
      var t = G.user.data.appVerstion ?? 'Version';
      vertionInfo =
          vertionInfo + t + '\n\n教APP备3700141号\n网络安全等级保护备案号\n37022050025-20001';
    });
  }

  @override
  void dispose() {
    oldPasswordInputController.dispose();
    newPasswordInputController.dispose();
    renewPasswordInputController.dispose();
    super.dispose();
  }

  @override
  void onCreate() {
    // log("onCreate");
  }

  @override
  void onPause() {}

  @override
  void onResume() {}
}
